package com.集合.TreeSet;
import java.util.TreeSet;
import java.util.Comparator;
public class TreeSetDemo {
    public static void main(String[] args){
//        TreeSet<Student> ts = new TreeSet<Student>();
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //按年龄排序
                int num = s1.getAge()-s2.getAge();
                //按姓名首字母顺序排序(年龄相同时)
                int num1 = num==0? s1.getName().compareTo(s2.getName()):num;
                return num1;
            }
        });

        Student s1 = new Student("xishi",20);
        Student s2 = new Student("wangzhaojun",24);
        Student s3 = new Student("diaochan",22);
        Student s4 = new Student("yangyuhuan",26);
        Student s5 = new Student("yangyuhuan",26);
        Student s6 = new Student("zhangsan",26);

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);

        for(Student s:ts){
            System.out.println(s);
        }

    }
}
/*结论:
* 1.TreeSet集合存储自定义对象，无参构造方法使用的是自然排序对元素进行排序
* 2.自然排序：让元素所属的类实现Comparable接口，重写compareTo()方法
* 3.自然排序和比较器排序可以实现相同的功能
* 只是前者在学生类上实现Comparable接口,后者在TreeSet构造方法中传递一个Comparator接口*/
